[CmdletBinding(DefaultParameterSetName = 'None')]
param
(
	[String]
	$DeploymentEnvironmentName,

	[String]
	$TeamProjectName,

	[String]
	$CollectionUrl
)

function Get-DeploymentEnvironment
{
    [CmdletBinding()]
    param
    (
        [String]
        [Parameter(Mandatory = $true)]
        $CollectionUrl = "",

        [String]
        [Parameter(Mandatory = $true)]
        $DeploymentEnvironmentName = "",

        [String]
        [Parameter(Mandatory = $true)]
        $TeamProjectName = ""
    )
    process
    {
        Add-Type -AssemblyName ('Microsoft.TeamFoundation.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL')
        Add-Type -AssemblyName ('Microsoft.TeamFoundation.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL')
        Add-Type -AssemblyName ('Microsoft.TeamFoundation.VersionControl.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL')
        Add-Type -AssemblyName ('Microsoft.TeamFoundation.VersionControl.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL')
        Add-Type -AssemblyName ('Microsoft.TeamFoundation.Build.Client, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL')
        Add-Type -AssemblyName ('Microsoft.TeamFoundation.Build.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL')

        $collectionUri = New-Object -TypeName "System.Uri" -ArgumentList $CollectionUrl
        $tfsCred = [Microsoft.TeamFoundation.Client.TfsClientCredentials]::LoadCachedCredentials([Microsoft.TeamFoundation.CredentialsStorageRegistryKeywords]::Build, $collectionUri, $false, $false)
        $tfsCollection = New-Object -TypeName "Microsoft.TeamFoundation.Client.TfsTeamProjectCollection" -ArgumentList $collectionUri, $tfsCred
        $deploymentService = $tfsCollection.GetService([Microsoft.TeamFoundation.Build.Client.DeploymentService])
        $deploymentEnvironment = $deploymentService.GetDeploymentEnvironment($DeploymentEnvironmentName, $TeamProjectName);
        return $deploymentEnvironment
    }
}

function Setup-AzureSubscription
{
    [CmdletBinding()]
    Param
    (
        [String]
        $AzureSubId,
        
        [String]
        $AzureSubName,
        
        [System.Security.Cryptography.X509Certificates.X509Certificate2]
        $X509Certificate,
        
        [String]
        $ServiceEndpoint = 'https://management.core.windows.net/',
        
        [Parameter(Mandatory=$false)]
        [Boolean]
        $IsDefault = $false
    )
    Process
    {
        Set-AzureSubscription -SubscriptionName $AzureSubName -SubscriptionId $AzureSubId -Certificate $X509Certificate -ServiceEndpoint $ServiceEndpoint
        
        if($IsDefault)
        {
            Select-AzureSubscription -SubscriptionName $AzureSubName -Default
        }

    }
}

function Get-X509Certificate
{
    [CmdletBinding()]
    param
    (
        [Xml]
        [Parameter(Mandatory = $true)]
        $CredentialsXml
    )
    process
    {
        
        $certBytes = [System.Convert]::FromBase64String($CredentialsXml.PublishData.PublishProfile.Subscription.ManagementCertificate)
        $x509Cert = New-Object -TypeName "System.Security.Cryptography.X509Certificates.X509Certificate2"
        $x509Cert.Import($certBytes);


        $x509StoreName = [System.Security.Cryptography.X509Certificates.StoreName]::My
        $x509StoreLocation = [System.Security.Cryptography.X509Certificates.StoreLocation]::CurrentUser
        $x509Store = New-Object -TypeName "System.Security.Cryptography.X509Certificates.X509Store" -ArgumentList $x509StoreName, $x509StoreLocation 
        $x509Store.Open([System.Security.Cryptography.X509Certificates.OpenFlags]::ReadWrite);
        $x509Store.Add($x509Cert);
        $x509Store.Close();
        return $x509Cert
    }
}

$deploymentEnvironment = Get-DeploymentEnvironment -CollectionUrl $CollectionUrl -DeploymentEnvironmentName $DeploymentEnvironmentName -TeamProjectName $TeamProjectName
$credentialsXml = [xml]$deploymentEnvironment.ConnectedService.CredentialsXml
$x509Cert = Get-X509Certificate -CredentialsXml $credentialsXml

$azureSubscriptionId = $credentialsXml.PublishData.PublishProfile.Subscription.Id
$azureSubscriptionName = $credentialsXml.PublishData.PublishProfile.Subscription.Name
$azureServiceEndpoint = $credentialsXml.PublishData.PublishProfile.Subscription.ServiceManagementUrl

Setup-AzureSubscription -AzureSubId $azureSubscriptionId  -AzureSubName $azureSubscriptionName  -X509Certificate $x509Cert -ServiceEndpoint $azureServiceEndpoint  -IsDefault $true

cd "$env:TF_BUILD_SOURCESDIRECTORY"
$website = $env:TF_BUILD_SOURCESDIRECTORY + "\PhpSite"

Publish-AzureWebsiteProject -Name $DeploymentEnvironmentName -Package $website
